/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.gingresos.searchs;

import javax.swing.table.DefaultTableModel;
import org.gingresos.start.MySesion;
import org.sirmupadbapi.beans.Contribuyentes;
import org.sirmupadbapi.controller.ContribuyentesController;
import org.sirmupadbapi.generales.Mensajeria;

/**
 *
 * @author avbravo
 */
public class jDialogContribuyentesSearch extends javax.swing.JDialog {

    DefaultTableModel modelo;
    int fila = -1;
    Contribuyentes contribuyentes1 = new Contribuyentes();
    ContribuyentesController contribuyentesController1 = new ContribuyentesController();
    String sql;
    boolean encontrado = false;

    /**
     * Creates new form jDialogContribuyentesSearch
     */
    public jDialogContribuyentesSearch(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();

        modelo = (DefaultTableModel) jTableContribuyentes.getModel();
        verTodos();

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jButtonAceptar = new javax.swing.JButton();
        jButtonCancelar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldCedula = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableContribuyentes = new javax.swing.JTable();
        jButtonBuscarCedula = new javax.swing.JButton();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldDireccion = new javax.swing.JTextField();
        jLabelMensaje = new javax.swing.JLabel();
        jButtonVerTodos = new javax.swing.JButton();
        jButtonNombre = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Busqueda Contribuyentes");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
        });

        jButtonAceptar.setText("Aceptar");
        jButtonAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAceptarActionPerformed(evt);
            }
        });

        jButtonCancelar.setText("Cancelar");
        jButtonCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelarActionPerformed(evt);
            }
        });

        jLabel1.setText("Nombre");

        jTextFieldNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNombreActionPerformed(evt);
            }
        });

        jLabel2.setText("Cedula");

        jTextFieldCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldCedulaActionPerformed(evt);
            }
        });

        jTableContribuyentes.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cedula", "Nombre", "Direccion", "Telefono"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableContribuyentes.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableContribuyentesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableContribuyentes);

        jButtonBuscarCedula.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/search.gif"))); // NOI18N
        jButtonBuscarCedula.setToolTipText("Buscar");
        jButtonBuscarCedula.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonBuscarCedulaActionPerformed(evt);
            }
        });

        jLabel3.setText("Direccion");

        jTextFieldDireccion.setEditable(false);

        jLabelMensaje.setFont(new java.awt.Font("Ubuntu", 1, 15)); // NOI18N
        jLabelMensaje.setText("De clic en el contribuyente de la lista...");

        jButtonVerTodos.setText("Ver Todos");
        jButtonVerTodos.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonVerTodosActionPerformed(evt);
            }
        });

        jButtonNombre.setIcon(new javax.swing.ImageIcon(getClass().getResource("/org/gingresos/resources/gif/search.gif"))); // NOI18N
        jButtonNombre.setToolTipText("Buscar");
        jButtonNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonNombreActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(21, 21, 21)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabelMensaje)
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jButtonAceptar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonVerTodos)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jButtonCancelar))
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 591, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel2))
                                .addGap(32, 32, 32)
                                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(jButtonBuscarCedula))
                                    .addGroup(jPanel1Layout.createSequentialGroup()
                                        .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 306, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                        .addComponent(jButtonNombre))))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addComponent(jLabel3)
                                .addGap(23, 23, 23)
                                .addComponent(jTextFieldDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, 394, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addContainerGap(44, Short.MAX_VALUE))))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonNombre))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(jTextFieldCedula, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jButtonBuscarCedula))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jTextFieldDireccion, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAceptar)
                    .addComponent(jButtonCancelar)
                    .addComponent(jButtonVerTodos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 293, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabelMensaje)
                .addContainerGap(13, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 21, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelarActionPerformed
        MySesion.limpiarContribuyente();
        dispose();
    }//GEN-LAST:event_jButtonCancelarActionPerformed

    private void jTableContribuyentesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableContribuyentesMouseClicked

        try {
            encontrado = true;
            fila = jTableContribuyentes.getSelectedRow();
            jTextFieldCedula.setText(jTableContribuyentes.getValueAt(fila, 0).toString());
            jTextFieldNombre.setText(jTableContribuyentes.getValueAt(fila, 1).toString());            
            jTextFieldDireccion.setText(jTableContribuyentes.getValueAt(fila, 2).toString());
            MySesion.setCedulaContribuyente(jTableContribuyentes.getValueAt(fila, 0).toString());
            MySesion.setNombreContribuyente(jTableContribuyentes.getValueAt(fila, 1).toString());
            MySesion.setDireccionContribuyente(jTableContribuyentes.getValueAt(fila, 2).toString());
            MySesion.setTelefonoContribuyente(jTableContribuyentes.getValueAt(fila, 3).toString());
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "table click");
        }

    }//GEN-LAST:event_jTableContribuyentesMouseClicked

    private void jButtonAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAceptarActionPerformed
     if(jTextFieldCedula.getText().isEmpty() || jTextFieldNombre.getText().isEmpty() || !encontrado ){
          MySesion.limpiarContribuyente();
          
          Mensajeria.Mensaje("No ha seleccionado ningun contribuyente de la lista");
          return;
      }
              
        dispose();
    }//GEN-LAST:event_jButtonAceptarActionPerformed

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    private void jButtonVerTodosActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonVerTodosActionPerformed
        verTodos();
    }//GEN-LAST:event_jButtonVerTodosActionPerformed

    private void jButtonBuscarCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonBuscarCedulaActionPerformed
        buscarCedula();
       
    }//GEN-LAST:event_jButtonBuscarCedulaActionPerformed

    private void jTextFieldNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldNombreActionPerformed
buscarNombre();
    }//GEN-LAST:event_jTextFieldNombreActionPerformed

    private void jTextFieldCedulaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldCedulaActionPerformed
buscarCedula();
    }//GEN-LAST:event_jTextFieldCedulaActionPerformed

    private void jButtonNombreActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonNombreActionPerformed
buscarNombre();
    }//GEN-LAST:event_jButtonNombreActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(jDialogContribuyentesSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(jDialogContribuyentesSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(jDialogContribuyentesSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(jDialogContribuyentesSearch.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the dialog
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                jDialogContribuyentesSearch dialog = new jDialogContribuyentesSearch(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    private void limpiarCampos(boolean cedula, boolean nombre){
        if(cedula){
          jTextFieldCedula.setText("");  
        }
        if(nombre){
            jTextFieldNombre.setText(""); 
        }
       
        jTextFieldDireccion.setText("");
    }
    private void buscarNombre(){
           encontrado = false;
           limpiarCampos(true,false);
         try {
            if (!jTextFieldNombre.getText().isEmpty()) {
                sql = "idmunicipio='" + MySesion.getIdmunicipio() + "' and activo='si' and contribuyente like '%" + jTextFieldNombre.getText() + "%' order by contribuyente";
                procesar(sql);
            }else{
                Mensajeria.Mensaje("Ingrese el nombre del contribuyente a buscar");
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "buscarNombre()");
        }
    }
    
    private void buscarCedula(){
        limpiarCampos(false,true);
        encontrado = false;
        try {
            if (!jTextFieldCedula.getText().isEmpty()) {
                sql = "idmunicipio='" + MySesion.getIdmunicipio() + "' and activo='si' and cedula like '%" + jTextFieldCedula.getText() + "%' order by contribuyente";
                procesar(sql);
            }else{
                Mensajeria.Mensaje("Ingrese el nombre del contribuyente a buscar");
            }
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "buscarCedula()");
        }
    }
    private void verTodos() {
        try {
            //encontrado = false;
            sql = "idmunicipio='" + MySesion.getIdmunicipio() + "' and activo='si' order by contribuyente";
           procesar(sql);
        } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "verTodos()");
        }
    }
    
    private void procesar(String sql){
       try{
           modelo = MySesion.limpiarModelo(modelo);
            if (contribuyentesController1.query(sql)) {
                Object[] filas = new Object[4]; // Hay tres columnas en la tabla
                for (Contribuyentes c : contribuyentesController1.getContribuyenteslist()) {
                    filas[0] = c.getCEDULA();
                    filas[1] = c.getCONTRIBUYENTE();
                    filas[2] = c.getDOMICILIO();
                    filas[3] = c.getTELEFONO();
                    modelo.addRow(filas);
                }
            } else {
                Mensajeria.Mensaje("No existen contribuyentes en este municipio");
            }
       } catch (Exception ex) {
            Mensajeria.MensajeError(ex, "procesar()");
        }
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAceptar;
    private javax.swing.JButton jButtonBuscarCedula;
    private javax.swing.JButton jButtonCancelar;
    private javax.swing.JButton jButtonNombre;
    private javax.swing.JButton jButtonVerTodos;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabelMensaje;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableContribuyentes;
    private javax.swing.JTextField jTextFieldCedula;
    private javax.swing.JTextField jTextFieldDireccion;
    private javax.swing.JTextField jTextFieldNombre;
    // End of variables declaration//GEN-END:variables
}
